package cn.xetsoft.supermarket.view;

import cn.xetsoft.supermarket.common.DataResponse;
import cn.xetsoft.supermarket.common.SystemData;
import cn.xetsoft.supermarket.entity.Order;
import cn.xetsoft.supermarket.entity.OrderItem;
import cn.xetsoft.supermarket.entity.User;
import cn.xetsoft.supermarket.service.Bean;
import cn.xetsoft.supermarket.service.OrderItemService;
import cn.xetsoft.supermarket.service.OrderService;
import cn.xetsoft.supermarket.util.DateUtil;
import cn.xetsoft.supermarket.util.GUITools;
import cn.xetsoft.supermarket.util.PropertiesUtil;
import cn.xetsoft.supermarket.util.ViewDataUtil;
import cn.xetsoft.supermarket.vo.OrderVo;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单页面
 */
@SuppressWarnings("serial")
public  class OrderFrame extends JDialog{
    //注册订单类服务
    private OrderService orderService = Bean.getOrderServiceInstance();


    private JTextField searchText = new JTextField(24);//添加计价单位文本框
    private JButton searchBtn = new JButton("搜索");//添加按钮
    private JScrollPane GoodsPane = new JScrollPane();//滚动视口
    protected JTable table = new JTable(){
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    private JLabel orderNumLabel = new JLabel("所有订单");//订单号
    private JLabel totalLabel = new JLabel();//总价
    private JLabel profitLabel = new JLabel();//利润
    private JLabel agentLabel = new JLabel(SystemData.getUser().getName());//经办人
    private JLabel OutTimeLabel = new JLabel(new Date().toString());//销售时间
    //添加功能组件
    private JButton dayBtn = new JButton("今日订单");//添加按钮
    //修改功能组件
    private JButton MonthBtn = new JButton("每月订单");//修改按钮
    //删除功能组件
    private JButton exportBtn = new JButton("导出EXCEL");//删除按钮
    //返回功能组件
    private JButton removeBtn = new JButton("删除");//删除按钮
    private JScrollPane scrollPane=new JScrollPane();
    private JLayeredPane layeredPane;
    private ImageIcon image;
    private JPanel jp;
    private JLabel jl;
    private JTextArea textArea = new JTextArea();

    //构造方法

    public OrderFrame() {
        this.init();// 初始化操作
        this.addComponent();// 添加组件
        this.addListener(this);// 添加监听器
    }
    // 初始化操作
    private void init() {
        this.setTitle("订单管理 - 熵客云超市管理");// 标题
        this.setSize(1286, 642);// 窗体大小与位置
        GUITools.center(this);//设置窗口在屏幕上的位置
        this.setResizable(false);// 窗体大小固定
        this.LoadingOrder(table);

        DataResponse<OrderVo> orderVoDataResponse = orderService.queryAll();
        if (orderVoDataResponse.isSuccess()){
            totalLabel.setText("总销售:"+orderVoDataResponse.getData().getTotalPrice());//总价
        }
        DataResponse<OrderVo> orderTotalProfit = orderService.queryAll();
        if (orderTotalProfit.isSuccess()){
            profitLabel.setText("总利润:"+orderTotalProfit.getData().getTotalProfit());//利润
        }

    }
    // 添加组件
    private void addComponent() {


        layeredPane=new JLayeredPane();
        /**
         * 得到路径区别开发环境和jar包
         */
        String imgFile = "Images/OrderBgImg.png";
        if (!PropertiesUtil.getProperty("debug.resources.type").equals("jar")){
            imgFile = Class.class.getResource("/").getPath() + imgFile;
        }
        image=new ImageIcon(imgFile);//随便找一张图就可以看到效果。
        //创建背景的那些东西
        jp=new JPanel();
        jp.setBounds(0,-10,image.getIconWidth(),642);

        jl=new JLabel(image);
        jl.setBounds(0,0,image.getIconWidth(),642);
        jp.add(jl);
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
        // tcr.setHorizontalAlignment(JLabel.CENTER);
        tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
        //搜索按钮

        //商品表格
        table.getTableHeader().setReorderingAllowed(false);	//列不能移动
        table.getTableHeader().setResizingAllowed(false); 	//不可拉动表格
//        table.setEnabled(false);							//不可更改数据
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.getTableHeader().setReorderingAllowed(false);
        table.setFillsViewportHeight(true);//确保表永远不会小于视图区
        table.setRowSelectionAllowed(true);//整行选择
//        addGoods(table);
        GoodsPane.setBounds(27, 178, 862, 435);
        //透明设置
//        GoodsPane.setOpaque(false);
//        GoodsPane.getViewport().setOpaque(false);
        GoodsPane.setViewportView(table);					//视口装入表格

        searchText.setBounds(32,120,451,50);
        searchText.setText("请输入订单号或指定日期的订单(格式:yyyy-mm-dd)");
        searchText.setForeground(Color.GRAY);

        orderNumLabel.setBounds(997, 228,130, 50);
        totalLabel.setBounds(980, 275,130, 50);
        profitLabel.setBounds(980, 315,130, 50);
        agentLabel.setBounds(999, 355,130, 50);
        OutTimeLabel.setBounds(1018, 395,130, 50);

        searchBtn.setBounds(483,120,160,50);
        dayBtn.setBounds(708, 120,130, 50);
        MonthBtn.setBounds(848, 120,128, 50);
        exportBtn.setBounds(986, 120,130, 50);
        removeBtn.setBounds(1123, 120,130, 50);
        textArea.setEnabled(false);
        scrollPane.setViewportView(textArea);
        scrollPane.setBounds(900,460,350,145);
        //将jp放到最底层。
        layeredPane.add(jp,JLayeredPane.DEFAULT_LAYER);

        //将jb放到高一层的地方
        layeredPane.add(GoodsPane,JLayeredPane.MODAL_LAYER);
        layeredPane.add(searchText,JLayeredPane.MODAL_LAYER);
        layeredPane.add(searchBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(dayBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(MonthBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(exportBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(removeBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(orderNumLabel,JLayeredPane.MODAL_LAYER);
        layeredPane.add(totalLabel,JLayeredPane.MODAL_LAYER);
        layeredPane.add(profitLabel,JLayeredPane.MODAL_LAYER);
        layeredPane.add(agentLabel,JLayeredPane.MODAL_LAYER);
        layeredPane.add(OutTimeLabel,JLayeredPane.MODAL_LAYER);
        layeredPane.add(scrollPane,JLayeredPane.MODAL_LAYER);


        this.setLayeredPane(layeredPane);
        this.setSize(image.getIconWidth(),667);
        this.setVisible(true);
        this.requestFocusInWindow();


    }
    // 添加监听器
    private void addListener(OrderFrame orderFrame) {
        searchBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String temp = searchText.getText();
                if (temp.equalsIgnoreCase("请输入订单号或指定日期的订单(格式:yyyy-mm-dd)")){
                    LoadingOrder(table);
                    return;
                }
                //判断是否是日期
                if (DateUtil.isDate(temp)){
                    DataResponse<OrderVo> orderVoDataResponse = orderService.queryByDate(temp);
                    //刷新表格
                    if (orderVoDataResponse.isSuccess()){
                        reflashTable(table, (ArrayList<Order>) orderVoDataResponse.getData().getOrders());
                    }else {
                        JOptionPane.showMessageDialog(null,"查询不到关于这个关键字的订单，换个搜索词试试看！");
                    }
                }else if (temp.equalsIgnoreCase("")){
                    LoadingOrder(table);
                }else {
                    DataResponse<List<Order>> orderDataResponse = orderService.queryByOrderNoLike(temp);
                    reflashTable(table, (ArrayList<Order>) orderDataResponse.getData());
                }

            }
        });
        //添加按钮监听
        dayBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //调用添加方法
//                new GoodsAddFrame().setVisible(true);
                DataResponse<OrderVo> orderVoDataResponse = orderService.queryByToday();
                if (orderVoDataResponse.isSuccess()){
                    JOptionPane.showMessageDialog(null,"查询成功！");
                    reflashTable(table, (ArrayList<Order>) orderVoDataResponse.getData().getOrders());
                }else {
                    JOptionPane.showMessageDialog(null,"查询今日的订单失败，也许是今日没有记录！");
                    return;
                }
//                orderFrame.setVisible(false);
            }
        });
        //修改按钮监听
        MonthBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //调用修改方法
                DataResponse<OrderVo> orderVoDataResponse = orderService.queryByNowMonth();
                if (orderVoDataResponse.isSuccess()){
                    JOptionPane.showMessageDialog(null,"查询成功！");
                    reflashTable(table, (ArrayList<Order>) orderVoDataResponse.getData().getOrders());
                }else {
                    JOptionPane.showMessageDialog(null,"查询本月的订单失败，也许是本月没有记录！");
                    return;
                }
            }
        });
        //导出按钮监听
        exportBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

//                new GoodsDeleteFrame().setVisible(true);
                new ExportDataFrame();
//                orderFrame.setVisible(false);
            }
        });

        searchText.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                String temp = searchText.getText();
                if (!temp.equals("")){
                    searchText.setText("");
                    searchText.setForeground(Color.BLACK);
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                String temp = searchText.getText();
                if (temp.equals("")){
                    searchText.setForeground(Color.GRAY);
                    searchText.setText("输入日期查询指定日期的订单(格式:yyyy-mm-dd)");
                }
            }
        });
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
               if (table.getSelectedRowCount() == 0 || table.getSelectedColumnCount() == 0){
                   JOptionPane.showMessageDialog(null,"尚未选中任何订单，无法查看！");
                   return;
               }
                String nowSelectOrderNo = table.getValueAt(table.getSelectedRow(),1).toString();
                DataResponse<Order> orderDataResponse = orderService.queryByOrderNo(nowSelectOrderNo);
                if (!orderDataResponse.isSuccess()){
                    JOptionPane.showMessageDialog(null,"当前订单查询失败，请重试!");
                    return;
                }
                orderNumLabel.setText(orderDataResponse.getData().getOrderNo());
                totalLabel.setText(orderDataResponse.getData().getTotalPrice() +"(总销售:"+orderService.queryAll().getData().getTotalPrice()+")");
                profitLabel.setText(orderDataResponse.getData().getProfit() +"(总利润:"+orderService.queryAll().getData().getTotalProfit()+")");
                agentLabel.setText(orderDataResponse.getData().getAgent());
                OutTimeLabel.setText(String.valueOf(orderDataResponse.getData().getSaleTime()));
//                textArea.append("购物商品显示");
                OrderItemService orderItemService = Bean.getOrderItemServiceInstance();
                DataResponse<List<OrderItem>> orderItemDataResponse = orderItemService.queryByOrderNo(String.valueOf(table.getValueAt(table.getSelectedRow(), 1)));
               if (orderItemDataResponse.isSuccess()){
                   List<OrderItem> data = orderItemDataResponse.getData();
                   textArea.setText(""); //清空文本域
                   for (OrderItem item : data) {
                       textArea.append("商品名:" + item.getGoodname() + "\r\n" + "商品品牌:" + item.getGoodbrand() + "\r\n" + "商品单价:" + item.getSalePrice() + "\r\n"  +  "计价单位:" + item.getType()  +"\r\n" + "购买数量:" + item.getQuantity() + "\r\n" +   "============\r\n");
                   }
               }else {
                   textArea.append("该订单无商品记录");
               }

            }
        });
        removeBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (table.getSelectedColumnCount() == 0 || table.getSelectedRowCount() == 0){
                    JOptionPane.showMessageDialog(null,"没有选中任何订单，无法删除！");
                    return;
                }
                String Order = table.getValueAt(table.getSelectedRow(),0).toString();
                if (JOptionPane.showConfirmDialog(null,"确认删除订单"+table.getValueAt(table.getSelectedRow(),1).toString()+"吗？","删除警告",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
                    DataResponse dataResponse = orderService.deleteById(Integer.valueOf(Order));
                    if (dataResponse.isSuccess()){
                        JOptionPane.showMessageDialog(null,"删除成功!");
                        LoadingOrder(table);
                    }else {
                        JOptionPane.showMessageDialog(null,"删除失败！");
                    }

                }
            }
        });
    }
    public void LoadingOrder(JTable table){
        ViewDataUtil viewDataUtil = new ViewDataUtil();
        String[][] tbody = new String[0][];
        DataResponse<OrderVo> orderVoDataResponse = orderService.queryAll();

        if (orderVoDataResponse.isSuccess()){//操作成功
            System.out.println(orderVoDataResponse.getData());
            ArrayList<Order> OrderList = (ArrayList<Order>) orderVoDataResponse.getData().getOrders();
            tbody = viewDataUtil.OrderToArrays(OrderList);
        } else {
            //不成功打印错误信息
            System.out.println(orderVoDataResponse.getMsg());
        }
        String[] thead = new String[]{"ID","订单号","描述","总价","利润","销售时间","上一次维护时间"};
        TableModel dataModel = new DefaultTableModel(tbody, thead);
        table.setModel(dataModel);
    }

    public void reflashTable(JTable table,ArrayList<Order> orderArrayList){
        ViewDataUtil viewDataUtil = new ViewDataUtil();
        String[][] tbody = viewDataUtil.OrderToArrays(orderArrayList);
        String[] thead = new String[]{"ID","订单号","描述","总价","利润","销售时间","上一次维护时间"};
        TableModel dataModel = new DefaultTableModel(tbody, thead);
        table.setModel(dataModel);
    }
}
